import router from '@/router/index'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { getLocalData } from '@/utils/tool'
import dayjs from 'dayjs'
import menuStore from '@/store/menu.ts'
import _ from 'lodash'
import { menuRoute } from '@/router/routes'


router.beforeEach((to, from, next) => {
  const token = getLocalData('zsnToken')
  const presence = to.path.includes('login')
  const menu = menuStore()
  if (token) {
    const startDate = dayjs(token)
    const endDate = dayjs()
    const diffInDays = endDate.diff(startDate, 'day')
    if (diffInDays > 1 && !presence) {
      menu.restoreOriginalData()
      next('/login') // 如果token过期且不是在登录页，则跳转到登录页
    } else {
      next()
    }
  } else if (!presence) {
    menu.restoreOriginalData()
    next('/login') // 如果没有token且不是在登录页，则继续路由导航
  } else {
    next() // 如果在登录页且没有token，则继续路由导航
  }
  nprogress.start()
})

router.afterEach((to, from) => {
  nprogress.done()
})


export const initRoute = () => {
  const menu = menuStore()
  const routes = menu.routes
  const cloneMenuRoutes = _.cloneDeep(menuRoute)
  if (routes) {
    const resRoute = cloneMenuRoutes.filter((item) => routes.includes(item.name))
    resRoute.forEach((item) => {
      const res = computeRoute(item, routes)
      const existingRoutes = router.getRoutes()
      const routeExists = existingRoutes.some((route: any) => route.name == res.name)
      if (routeExists) router.removeRoute(res.name!) // 添加之前移除 避免重复
      router.addRoute(res)
      const existence = router.options.routes.find((el: any) => el.name == item.name)
      if (!existence) router.options.routes = [...router.options.routes, ...resRoute]
    })
  }
}

const computeRoute = (route: any, routeNames: any) => {
  if (!route.children && routeNames.includes(route.name)) return route
  if (route.children && routeNames.includes(route.name)) {
    const children = []
    for (const al of route.children) {
      const a = computeRoute(al, routeNames)
      if (a) children.push(a)
    }
    route.children = children
    return route
  }
}